package leetcodev1.树;

import java.util.LinkedList;
import java.util.Queue;

public class LeetCode117 {
    //层次遍历
    public Node connect(Node root) {
        if (root == null) {
            return root;
        }

        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Node pre = null;
            for (int i = 0; i < size; i++) {
                Node poll = queue.poll();
                if (poll.left != null) {
                    queue.add(poll.left);
                }

                if (poll.right != null) {
                    queue.add(poll.right);
                }

                if (i == 0) {
                    pre = poll;
                } else {
                    pre.next = poll;
                    pre = pre.next;
                }

            }
        }

        return root;
    }
}
